/*
 * Copyright 2002-2021 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.context.support;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.core.OrderComparator;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import org.springframework.core.metrics.ApplicationStartup;
import org.springframework.core.metrics.StartupStep;
import org.springframework.lang.Nullable;

/**
 * Delegate for AbstractApplicationContext's post-processor handling.
 *
 * @author Juergen Hoeller
 * @author Sam Brannen
 * @since 4.0
 */
final class PostProcessorRegistrationDelegate {

	private PostProcessorRegistrationDelegate() {
	}


	/**
	 * BeanFactoryPostProcessors按入场方式分为： 1. 程序员调用ApplicationContext的API手动添加 2. Spring自己扫描出来的 如：context.addBeanFactoryPostProcessor(new MyBeanDefinitionRegistryPostProcessor());
	 * <p>
	 * BeanFactoryPostProcessor按类型又可以分为： 1. 普通BeanFactoryPostProcessor 2. BeanDefinitionRegistryPostProcessor
	 * <p>
	 * 执行顺序顺序如下： 1. 执行手动添加的BeanDefinitionRegistryPostProcessor                       的postProcessBeanDefinitionRegistry()方法 2. 执行扫描出来的BeanDefinitionRegistryPostProcessor（实现了PriorityOrdered）的postProcessBeanDefinitionRegistry()方法 3. 执行扫描出来的BeanDefinitionRegistryPostProcessor（实现了Ordered） 的postProcessBeanDefinitionRegistry()方法 4. 执行扫描出来的BeanDefinitionRegistryPostProcessor（普通）				   的postProcessBeanDefinitionRegistry()方法 5. 执行扫描出来的BeanDefinitionRegistryPostProcessor（所有） 的postProcessBeanFactory()方法 6. 执行手动添加的BeanFactoryPostProcessor								   的postProcessBeanFactory()方法 7. 执行扫描出来的BeanFactoryPostProcessor（实现了PriorityOrdered）		   的postProcessBeanFactory()方法 8. 执行扫描出来的BeanFactoryPostProcessor（实现了Ordered）		   		   的postProcessBeanFactory()方法 9. 执行扫描出来的BeanFactoryPostProcessor（普通）				   		   的postProcessBeanFactory()方法
	 * <p>
	 * ConfigurationClassPostProcessor就会在第2步执行，会进行扫描
	 */
	public static void invokeBeanFactoryPostProcessors(
			ConfigurableListableBeanFactory beanFactory,
			List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

		// 在普通默认情况下beanFactory中的PostProcessors 里面包含了框架自己初始化的5个，我们自己添加的AppConfig
		// 当前方法的beanFactoryPostProcessors为0

		// =======================================================================================================================
		// 这里面存的是已经执行的后置处理器
		Set<String> processedBeans = new HashSet<>();

		//  beanFactory = DefaultListableBeanFactory
		// DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements
		// ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable
		// 这个beanFactory指定是BeanDefinitionRegistry类的
		if (beanFactory instanceof BeanDefinitionRegistry) {

			BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
			// =======================================================================================================================
			// 常规BeanFactoryPostProcessor
			List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
			// 存放所有的BeanDefinitionRegistryPostProcessor
			// 存放所有内置的BeanFactoryPostProcessor
			List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
			// =======================================================================================================================
			// beanFactoryPostProcessors集合一般情况下都是空的，除非我们手动调用容器的addBeanFactoryPostProcessor方法添加了
			// beanFactoryPostProcessors中可能包含了：普通BeanFactoryPostProcessor对象和BeanDefinitionRegistryPostProcessor对象
			// 对于BeanDefinitionRegistryPostProcessor对象，会执行自己的postProcessBeanDefinitionRegistry()方法
			// 这里是Spring是想先执行开发人员自己定义的BeanDefinitionRegistryPostProcessor后置处理器
			// 进行分类，分类很重要
			for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
				if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
					//
					BeanDefinitionRegistryPostProcessor registryProcessor = (BeanDefinitionRegistryPostProcessor) postProcessor;
					// Spring 负责调用，这里面之前说过，可以进行BeanDefinition的注册
					registryProcessor.postProcessBeanDefinitionRegistry(registry);
					registryProcessors.add(registryProcessor);
				} else {
					// 分类的时候，将BeanFactoryPostProcessor按照分类存储，
					// TODO 为什么没有执行postProcessBeanFactory？
					// 因为Spring觉得这个需要在postProcessBeanDefinitionRegistry执行完之后再执行
					// 首先得保证Spring自己的框架初始化不受我们自己添加的BeanDefinitionRegistryPostProcessor实现影响
					regularPostProcessors.add(postProcessor);
				}
			}
			// =======================================================================================================================
			// Do not initialize FactoryBeans here: We need to leave all regular beans
			// uninitialized to let the bean factory post-processors apply to them!
			// Separate between BeanDefinitionRegistryPostProcessors that implement
			// PriorityOrdered, Ordered, and the rest.
			// 接下来要执行的所有的策略对象
			List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

			// 执行扫描出来的BeanDefinitionRegistryPostProcessor
			// 这句话本身的意思就是，从已存在的BeanDefinitionMap中找到实现了BeanDefinitionRegistryPostProcessor接口的类
			// 从BeanDefinition的列表中找到ConfigurationClassPostProcessor。
			// 此处在执行 getBeanNamesForType -> doGetBeanNamesForType 是，BeanDefinitionMap中的BeanDefinition仅有6个
			// 一个是我们通过AnnotationConfigApplicationContext构造函数传入的AppConfig
			// 另外五个是Spring框架在执行初始化AnnotatedBeanDefinitionReader时注入的
			//0 = "org.springframework.context.annotation.internalConfigurationAnnotationProcessor"
			//1 = "org.springframework.context.annotation.internalAutowiredAnnotationProcessor"
			//2 = "org.springframework.context.annotation.internalCommonAnnotationProcessor"
			//3 = "org.springframework.context.event.internalEventListenerProcessor"
			//4 = "org.springframework.context.event.internalEventListenerFactory"
			// 另外还有4个环境变量的手动注入的BeanDefinition，manualSingletonNames，当然也可以使用context.registerSingleton 注入更多的手动Bean。
			// 也就是说，我们新建一个Bean注入其中也会生效，代码如下：
			//context.getBeanFactory().registerSingleton("myBeanDefinitionRegistryPostProcessor", new MyBeanDefinitionRegistryPostProcessor());
			// 还有，我们也可以再手动注入一个BeanDefinition，代码如下：
			//AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
			//beanDefinition.setBeanClass(MyBeanDefinitionRegistryPostProcessor.class);
			//context.registerBeanDefinition("myBeanDefinitionRegistryPostProcessor",beanDefinition);
			String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			for (String ppName : postProcessorNames) {
				if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
					//为什么这里就可以getBean了？直接从容器拿，如果拿不到会new。
					//子路老师说，因为这里有bd，所以可以，另一个方面说，Spring只要有bd就可以实例化。
					//这行代码会实例化这个ConfigurationClassPostProcessor类
					//为什么要弄List来存？自己可以开发（临时变量）
					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					processedBeans.add(ppName);
				}
			}
			// 为什么有这些步骤？直接把处理器填充到registryProcessors不行吗？
			// 升序排序
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			registryProcessors.addAll(currentRegistryProcessors);
			// 这里执行的是从BeanDefinition中找到的BeanDefinitionRegistryPostProcessor后置处理，并执行
			// 1、此时包含了Spring内置的ConfigurationClassPostProcessor，执行了AppConfig配置的解析
			// 2、开发自己的定义的MyBeanDefinitionRegistryPostProcessor
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
			currentRegistryProcessors.clear();
			// =======================================================================================================================
			//
			//调用实现 Ordered 的 BeanDefinitionRegistryPostProcessors。
			postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			for (String ppName : postProcessorNames) {
				// processedBeans表示该beanFactoryPostProcessor的postProcessBeanDefinitionRegistry()方法已经执行过了，不再重复执行
				if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					processedBeans.add(ppName);
				}
			}
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			registryProcessors.addAll(currentRegistryProcessors);
			// 执行实现了Order接口的BeanDefinitionRegistryPostProcessors后置处理器
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
			currentRegistryProcessors.clear();
			// =======================================================================================================================
			// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
			// 执行哪些没有实现了PriorityOrdered或Ordered接口的普通BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry()方法
			// 在这个过程中可能会向BeanFactory中注册另外的BeanDefinitionRegistryPostProcessor，所以需要while，直到确定所有的BeanDefinitionRegistryPostProcessor都执行完了
			// 在这个过程中注册的BeanDefinitionRegistryPostProcessor，所实现的PriorityOrdered或Ordered接口可能会不按顺序执行
			// 比如 A注册了B和C,B又注册了D和E,那么B和C会按顺序执行，D和E也会按顺序执行，但是B、C、D、E整体不能保证是顺序执行
			boolean reiterate = true;
			//这个循环是为了保证我们在postProcessBeanDefinitionRegistry方法里面再次注册BeanDefinitionRegistryPostProcessor的BeanDefinition
			while (reiterate) {
				reiterate = false;
				// 只要实现BeanDefinitionRegistryPostProcessor
				postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
				for (String ppName : postProcessorNames) {
					// 如果未执行的，将未执行的全部执行一遍
					if (!processedBeans.contains(ppName)) {
						currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
						processedBeans.add(ppName);
						// 为什么又设置为true？
						//  直到再也找不到postProcessorNames时，终止循环
						reiterate = true;
					}
				}
				sortPostProcessors(currentRegistryProcessors, beanFactory);
				registryProcessors.addAll(currentRegistryProcessors);
				//
				invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
				currentRegistryProcessors.clear();
			}
			// =======================================================================================================================

			// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
			// 执行完BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry()方法后，
			// 再执行BeanDefinitionRegistryPostProcessor的postProcessBeanFactory()方法
			// 允许子容器添加PostProsessor
			invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);

			// 执行手动添加的普通BeanFactoryPostProcessor的postProcessBeanFactory()方法\
			// 允许子容器添加PostProsessor
			invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
		} else {
			// Invoke factory processors registered with the context instance.
			invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
		}

		// 执行扫描出来的普通BeanFactoryPostProcessor，主要是用来执行postProcessBeanFactory增加方法

		// Do not initialize FactoryBeans here: We need to leave all regular beans
		// uninitialized to let the bean factory post-processors apply to them!
		String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

		// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
		// Ordered, and the rest.
		List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
		List<String> orderedPostProcessorNames = new ArrayList<>();
		List<String> nonOrderedPostProcessorNames = new ArrayList<>();
		// 先进行分类
		for (String ppName : postProcessorNames) {
			if (processedBeans.contains(ppName)) {
				// skip - already processed in first phase above
			} else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
				priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
			} else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
				orderedPostProcessorNames.add(ppName);
			} else {
				nonOrderedPostProcessorNames.add(ppName);
			}
		}

		// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
		sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
		invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

		// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
		List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
		for (String postProcessorName : orderedPostProcessorNames) {
			orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
		}
		sortPostProcessors(orderedPostProcessors, beanFactory);
		invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

		// Finally, invoke all other BeanFactoryPostProcessors.
		List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
		for (String postProcessorName : nonOrderedPostProcessorNames) {
			nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
		}
		invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

		// Clear cached merged bean definitions since the post-processors might have
		// modified the original metadata, e.g. replacing placeholders in values...
		beanFactory.clearMetadataCache();
	}

	public static void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {

		// org.springframework.context.annotation.internalAutowiredAnnotationProcessor
		// org.springframework.context.annotation.internalCommonAnnotationProcessor
		// 这里默认会找到AutowiredAnnotationProcessor、CommonAnnotationProcessor两个后置处理器
		// =======================================================================================================================
		// BeanPostProcessor ==> 他有两个原生方法，分别在bean的初始化前后调用，方法如下：
		// postProcessBeforeInitialization(Object bean, String beanName)  初始化前
		// postProcessAfterInitialization(Object bean, String beanName)   初始化后
		// bean对象创建的4个阶段：实例化 ==> 属性填充 ==> 初始化 ==> bean
		// =======================================================================================================================
		// 那么问题来了，这两个对象为什么会被找到呢？
		// 在 AnnotationConfigApplicationContext的构造函数中 ==>
		// AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry) ==> 将Spring框架一些默认用到的后置处理器给内置进去
		// =======================================================================================================================
		String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

		// Register BeanPostProcessorChecker that logs an info message when
		// a bean is created during BeanPostProcessor instantiation, i.e. when
		// a bean is not eligible for getting processed by all BeanPostProcessors.
		// beanProcessorTargetCount表示BeanFactory中所有的BeanPostProcessor数量，+1表示BeanPostProcessorChecker
		int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
		beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

		// 存储优先级、有序的PostProcessors，这里主要是应对程序员自己添加的一些PostProcessors
		List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
		// 存储内置的PostProcessors
		List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
		List<String> orderedPostProcessorNames = new ArrayList<>();
		List<String> nonOrderedPostProcessorNames = new ArrayList<>();
		// 遍历找到的BeanPostProcessor
		for (String ppName : postProcessorNames) {
			// 容器中的这个postProcessor实现了PriorityOrdered接口
			if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
				BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
				priorityOrderedPostProcessors.add(pp);
				// 如果容器中的这个postProcessor实现了MergedBeanDefinitionPostProcessor接口
				if (pp instanceof MergedBeanDefinitionPostProcessor) {
					internalPostProcessors.add(pp);
				}
			} else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
				orderedPostProcessorNames.add(ppName);
			} else {
				nonOrderedPostProcessorNames.add(ppName);
			}
		}

		// First, register the BeanPostProcessors that implement PriorityOrdered.
		// 升序排序
		sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
		registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

		// Next, register the BeanPostProcessors that implement Ordered.
		List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
		for (String ppName : orderedPostProcessorNames) {
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			orderedPostProcessors.add(pp);
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				internalPostProcessors.add(pp);
			}
		}
		sortPostProcessors(orderedPostProcessors, beanFactory);
		registerBeanPostProcessors(beanFactory, orderedPostProcessors);

		// Now, register all regular BeanPostProcessors.
		List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
		for (String ppName : nonOrderedPostProcessorNames) {
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			nonOrderedPostProcessors.add(pp);
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				internalPostProcessors.add(pp);
			}
		}
		registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

		// Finally, re-register all internal BeanPostProcessors.
		// MergedBeanDefinitionPostProcessor排在最后
		sortPostProcessors(internalPostProcessors, beanFactory);
		// 把定义了实现MergedBeanDefinitionPostProcessor接口的PostProcessor覆盖前面的。
		registerBeanPostProcessors(beanFactory, internalPostProcessors);

		// Re-register post-processor for detecting inner beans as ApplicationListeners,
		// moving it to the end of the processor chain (for picking up proxies etc).
		// ApplicationListenerDetector放在所有BeanPostProcessor之后，注意ApplicationListenerDetector的equals()方法实现
		// =======================================================================================================================
		// 前面的 prepareBeanFactory 已经将PostProcessor添加了一次，为什么这里还要覆盖一次呢？作用是什么？
		// TODO 分析： 放最后？后续理解深入了再回来理解这个
		//
		// =======================================================================================================================
		beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
	}

	private static void sortPostProcessors(List<?> postProcessors, ConfigurableListableBeanFactory beanFactory) {
		// Nothing to sort?
		if (postProcessors.size() <= 1) {
			return;
		}
		Comparator<Object> comparatorToUse = null;
		if (beanFactory instanceof DefaultListableBeanFactory) {
			comparatorToUse = ((DefaultListableBeanFactory) beanFactory).getDependencyComparator();
		}
		if (comparatorToUse == null) {
			comparatorToUse = OrderComparator.INSTANCE;
		}
		postProcessors.sort(comparatorToUse);
	}

	/**
	 * Invoke the given BeanDefinitionRegistryPostProcessor beans.
	 */
	private static void invokeBeanDefinitionRegistryPostProcessors(
			Collection<? extends BeanDefinitionRegistryPostProcessor> postProcessors,
			BeanDefinitionRegistry registry,
			ApplicationStartup applicationStartup) {

		for (BeanDefinitionRegistryPostProcessor postProcessor : postProcessors) {
			StartupStep postProcessBeanDefRegistry = applicationStartup.start("spring.context.beandef-registry.post-process")
					.tag("postProcessor", postProcessor::toString);
			//
			postProcessor.postProcessBeanDefinitionRegistry(registry);
			postProcessBeanDefRegistry.end();
		}
	}

	/**
	 * Invoke the given BeanFactoryPostProcessor beans.
	 */
	private static void invokeBeanFactoryPostProcessors(Collection<? extends BeanFactoryPostProcessor> postProcessors, ConfigurableListableBeanFactory beanFactory) {

		for (BeanFactoryPostProcessor postProcessor : postProcessors) {
			StartupStep postProcessBeanFactory = beanFactory.getApplicationStartup().start("spring.context.bean-factory.post-process")
					.tag("postProcessor", postProcessor::toString);
			// 允许子容器添加 PostProsessor
			// 允许用来修改 BeanDefinition。
			postProcessor.postProcessBeanFactory(beanFactory);
			postProcessBeanFactory.end();
		}
	}

	/**
	 * Register the given BeanPostProcessor beans.
	 */
	private static void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors) {

		if (beanFactory instanceof AbstractBeanFactory) {
			// Bulk addition is more efficient against our CopyOnWriteArrayList there
			((AbstractBeanFactory) beanFactory).addBeanPostProcessors(postProcessors);
		} else {
			for (BeanPostProcessor postProcessor : postProcessors) {
				beanFactory.addBeanPostProcessor(postProcessor);
			}
		}
	}


	/**
	 * BeanPostProcessor that logs an info message when a bean is created during BeanPostProcessor instantiation, i.e. when a bean is not eligible for getting processed by all BeanPostProcessors.
	 */
	private static final class BeanPostProcessorChecker implements BeanPostProcessor {

		private static final Log logger = LogFactory.getLog(BeanPostProcessorChecker.class);

		private final ConfigurableListableBeanFactory beanFactory;

		private final int beanPostProcessorTargetCount;

		public BeanPostProcessorChecker(ConfigurableListableBeanFactory beanFactory, int beanPostProcessorTargetCount) {
			this.beanFactory = beanFactory;
			this.beanPostProcessorTargetCount = beanPostProcessorTargetCount;
		}

		@Override
		public Object postProcessBeforeInitialization(Object bean, String beanName) {
			return bean;
		}

		@Override
		public Object postProcessAfterInitialization(Object bean, String beanName) {
			// 在创建某个BeanPostProcessor的时候，额外还创建了一个其他的Bean
			// getBeanPostProcessorCount()拿到的是beanPostProcessors是的值，beanPostProcessorTargetCount是BeanPostProcessor对应的BeanDefinition的个数
			if (!(bean instanceof BeanPostProcessor) && !isInfrastructureBean(beanName) &&
					this.beanFactory.getBeanPostProcessorCount() < this.beanPostProcessorTargetCount) {
				if (logger.isInfoEnabled()) {
					logger.info("Bean '" + beanName + "' of type [" + bean.getClass().getName() +
							"] is not eligible for getting processed by all BeanPostProcessors " +
							"(for example: not eligible for auto-proxying)");
				}
			}
			return bean;
		}

		private boolean isInfrastructureBean(@Nullable String beanName) {
			if (beanName != null && this.beanFactory.containsBeanDefinition(beanName)) {
				BeanDefinition bd = this.beanFactory.getBeanDefinition(beanName);
				return (bd.getRole() == RootBeanDefinition.ROLE_INFRASTRUCTURE);
			}
			return false;
		}
	}

}
